#!/usr/bin/python
#coding:utf-8

import requests
import re
from random import choice
import socket

class get_proxy():
    _list_proxy = []
    def __init__(self):
        pass
    
    def get_proxy(self):
	while len(self._list_proxy) == 0:
	    self._get_proxy_list()
	
	proxy = ''
	while len(self._list_proxy) != 0:
	    proxy = self._list_proxy.pop()
	    if self._check_proxy_socket(proxy):
		break
	else:
	    return self.get_proxy()
	    
	return proxy
	    
    def _get_proxy_list(self):
	print 'get_proxy'
	headers = {
'Host':'www.freeproxylists.net',
'User-Agent':'Mozilla/150.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3',
'Accept-Encoding':'gzip, deflate',
'Accept-Charset':'windows-1251,utf-8;q=0.7,*;q=0.7',
'Connection':'keep-alive',
'Cache-Control':'max-age=0',
'Cookie':'hl=ru; pv=9; userno=20111023-22337; from=direct;'}
	page = 1
	try:
	    req = requests.get('http://www.freeproxylists.net/ru/?page=' + str(page), headers=headers)
	    if req:
		match = re.findall('<td>([0-9.]+)</td><td align="center">(\d+)</td>', req.content)
		self._list_proxy = [":".join(x) for x in match]
	except msg:
	    print msg
    

    def _check_proxy(self, proxy):
	try:
	    req = requests.get('http://mathiasbynens.be/demo/css-without-html', timeout=10, proxies={'http':proxy})
	except:
	    return False

	if req.status_code == 200:
		return True
	return False
	
    def _check_proxy_socket(self, proxy):
	try:
	    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	    addr = proxy.split(":")
	    sock = sock.connect((addr[0], int(addr[1])))
	except:
	    sock.close()
	    return False
	
	sock.close()
	return True
	